package com.song.oscsong.fragment;


import org.apache.http.Header;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.song.oscsong.R;
import com.song.oscsong.adapter.NewsAdapter;
import com.song.oscsong.api.CacheManger;
import com.song.oscsong.api.OSCChinaApi;
import com.song.oscsong.bean.NewsList;
import com.song.oscsong.utils.XmlUtils;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

public class NewsFragment extends Fragment{
	
	
	private static String CACHE_PREFIX="news_";
	
	private ListView mListView;
	
	private int mCatalog;
	
	private int mPage;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		View v = inflater.inflate(R.layout.fragment_pull_refresh_listview, container ,false);
		mListView = (ListView) v.findViewById(R.id.listview);
		String key = getCachePrefix()+"_"+mPage; 
		if( CacheManger.isExistDataCache(getActivity(), key))
		{
			NewsList newsList = (NewsList) CacheManger.readObject(getActivity(), key);
			NewsAdapter newsAdapter = new NewsAdapter(newsList.getList());
			mListView.setAdapter(newsAdapter);
		}else{
			
			OSCChinaApi.getNewsList(mCatalog, mPage, new AsyncHttpResponseHandler() {
				
				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] data) {
					NewsList newsList =  XmlUtils.toBean(NewsList.class, data);
					NewsAdapter newsAdapter = new NewsAdapter(newsList.getList());
					CacheManger.saveObject(getActivity(), newsList, getCachePrefix()+"_"+mPage);
					mListView.setAdapter(newsAdapter);
				}
				
				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
					// TODO Auto-generated method stub
					
				}
			});
			
		}
		
		return v;
		
	}

	public String getCachePrefix()
	{
		return CACHE_PREFIX+mCatalog;
	}
	
}
